<?php

namespace backend\modules\business\controllers;

use backend\controllers\AdminController;
use common\models\business\BusinessContractCategory;
use common\models\business\BusinessCost;
use common\models\business\BusinessPig;
use common\models\business\BusinessVaccineSet;
use Yii;
use common\models\business\BusinessVaccine;
use backend\modules\business\models\BusinessVaccineSearch;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use yii\helpers\Url;
use yii\helpers\VarDumper;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * VaccineController implements the CRUD actions for BusinessVaccine model.
 */
class VaccineController extends AdminController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all BusinessVaccine models.
     * @return mixed
     */
    public function actionIndex()
    {
        $searchModel = new BusinessVaccineSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $sets = BusinessVaccineSet::find()->select('id,vaccinename')->asArray()->all();
        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
            'vaccset' => $sets
        ]);
    }

    /**
     * Displays a single BusinessVaccine model.
     * @param string $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new BusinessVaccine model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new BusinessVaccine();

        if ($model->load(Yii::$app->request->post())) {
            $setmodel = BusinessVaccineSet::findOne($model->vaccineid);
            $model->vaccinename = $setmodel->vaccinename;
            if($model->save()){
                //顺带添加一项成本
                $costdata = [
                    'pigid' => $model->pigid,
                    'type' => '疫苗',
                    'personid' => 0,
                    'person' => '后台',
                    'price' => $setmodel->price,
                    'description' => $model->remark,
                    'createtime' => time()
                ];
                $res = \Yii::$app->db->createCommand()->insert(BusinessCost::tableName(),$costdata)->execute();

                return $this->redirect(['view', 'id' => $model->id]);
            }
        } else {
            $vaccineset = BusinessVaccineSet::find()->select('id,vaccinename')->asArray()->all();
            return $this->render('create', [
                'model' => $model,
                'vaccineset' => $vaccineset
            ]);
        }
    }

    /**
     * Updates an existing BusinessVaccine model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param string $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post())) {
            $setmodel = BusinessVaccineSet::findOne($model->vaccineid);
            $model->vaccinename = $setmodel->vaccinename;
            $date = $model->date;
            if($model->save()){
                Yii::$app->db->createCommand()->update(BusinessVaccine::tableName(),['date'=>$date],['id'=>$model->id])->execute();
                return $this->redirect(['index']);
            }
        } else {
            $vaccineset = BusinessVaccineSet::find()->select('id,vaccinename')->asArray()->all();
            return $this->render('update', [
                'model' => $model,
                'vaccineset' => $vaccineset
            ]);
        }
    }

    /**
     * Deletes an existing BusinessVaccine model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param string $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }





    /**
     * Finds the BusinessVaccine model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param string $id
     * @return BusinessVaccine the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = BusinessVaccine::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }


    public function actionSetvaccine()
    {
        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            $basenum = $postdata['basenum'];
            $endnum = $postdata['endnum'];

            if($basenum<0 || $endnum<0){
                return $this->dialog('编号不能为负数');
            }

            $numlen = strlen($endnum);

            for ($i = $basenum; $i <= $endnum; $i++){
                $data[] = $postdata['formatno'].sprintf("%0{$numlen}d",$i);
            }
            $idarr = (new Query())->select('id')->from(BusinessPig::tableName())->where(['no'=>$data])->all();
            if(empty($idarr)){
                return $this->dialog('此范围没有对应的仔猪,请检查您输入的编号范围');
            }
            $vaccname = BusinessVaccineSet::findOne($postdata['vaccineid'])->vaccinename;
            foreach ($idarr as $k => $v){
                $data = [
                    'remark' => $postdata['remark'],
                    'date' => strtotime($postdata['date']),
                    'createtime' => time(),
                    'pigid' => $v['id'],
                    'vaccinename' => $vaccname,
                    'vaccineid' => $postdata['vaccineid']
                    ];
                $res = Yii::$app->db->createCommand()->insert(BusinessVaccine::tableName(),$data)->execute();
            }


            return $res?$this->dialog('设置成功','success'):$this->dialog('设置失败');
        }
    }


    /**
     *
     * 批量更改
     */
    public function actionBatchupdate()
    {
        if(Yii::$app->request->isPost){
            $postdata = Yii::$app->request->post();
            if(empty($postdata['ids'])){
                return $this->dialog('请选择要修改的疫苗');
            }
            $postdata['ids'] = explode(',',$postdata['ids']);
            $idarr = (new Query())->select('id')->from(BusinessVaccine::tableName())->where(['id'=>$postdata['ids']])->all();

            $ids = ArrayHelper::getColumn($idarr,'id');
            $vaccname = BusinessVaccineSet::findOne($postdata['vaccineid'])->vaccinename;
            $data = [
                'remark' => $postdata['remark'],
                'date' => strtotime($postdata['date']),
                'vaccinename' => $vaccname,
                'vaccineid' => $postdata['vaccineid']
            ];
            $res = Yii::$app->db->createCommand()->update(BusinessVaccine::tableName(),$data,['id'=>$idarr])->execute();
            return $res?$this->dialog('设置成功','success'):$this->dialog('设置失败');
        }


        $sets = BusinessVaccineSet::find()->select('id,vaccinename')->asArray()->all();
        return $this->renderPartial('_batchupdate',[
            'ids' => Yii::$app->request->get('ids'),
            'vaccset' => $sets
        ]);
    }


    /**
     * @return string
     * 批量删除
     */
    public function actionMutiDelete()
    {
        $ids = Yii::$app->request->post('ids');
        if(!empty($ids)){
            $res = Yii::$app->db->createCommand()->delete(BusinessVaccine::tableName(),['id'=>$ids])->execute();
            return $res?\GuzzleHttp\json_encode(['msg'=>'操作成功','status'=>0]):\GuzzleHttp\json_encode(['msg'=>'操作失败','status'=>1]);
        }

        return \GuzzleHttp\json_encode(['msg'=>'请选择对应的记录','status'=>1]);

    }
}
